// 星际网咖通用工具函数

// 格式化时间
export const formatTime = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
  if (!date) return ''
  
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hour = String(d.getHours()).padStart(2, '0')
  const minute = String(d.getMinutes()).padStart(2, '0')
  const second = String(d.getSeconds()).padStart(2, '0')
  
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hour)
    .replace('mm', minute)
    .replace('ss', second)
}

// 格式化相对时间
export const formatRelativeTime = (date) => {
  if (!date) return ''
  
  const now = new Date()
  const target = new Date(date)
  const diff = now.getTime() - target.getTime()
  
  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  const week = 7 * day
  const month = 30 * day
  
  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`
  } else if (diff < week) {
    return `${Math.floor(diff / day)}天前`
  } else if (diff < month) {
    return `${Math.floor(diff / week)}周前`
  } else {
    return formatTime(date, 'MM-DD')
  }
}

// 格式化金额
export const formatMoney = (amount, decimals = 2) => {
  if (amount === null || amount === undefined) return '0.00'
  
  const num = Number(amount)
  if (isNaN(num)) return '0.00'
  
  return num.toFixed(decimals)
}

// 格式化手机号
export const formatPhone = (phone) => {
  if (!phone) return ''
  
  const str = String(phone)
  if (str.length === 11) {
    return str.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')
  }
  return phone
}

// 验证手机号
export const validatePhone = (phone) => {
  const reg = /^1[3-9]\d{9}$/
  return reg.test(phone)
}

// 验证邮箱
export const validateEmail = (email) => {
  const reg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return reg.test(email)
}

// 防抖函数
export const debounce = (func, wait) => {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

// 节流函数
export const throttle = (func, limit) => {
  let inThrottle
  return function executedFunction(...args) {
    if (!inThrottle) {
      func.apply(this, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

// 深拷贝
export const deepClone = (obj) => {
  if (obj === null || typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj.getTime())
  if (obj instanceof Array) return obj.map(item => deepClone(item))
  if (typeof obj === 'object') {
    const clonedObj = {}
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key])
      }
    }
    return clonedObj
  }
}

// 生成唯一ID
export const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2)
}

// 显示加载提示
export const showLoading = (title = '加载中...') => {
  uni.showLoading({
    title,
    mask: true
  })
}

// 隐藏加载提示
export const hideLoading = () => {
  uni.hideLoading()
}

// 显示成功提示
export const showSuccess = (title, duration = 2000) => {
  uni.showToast({
    title,
    icon: 'success',
    duration
  })
}

// 显示错误提示
export const showError = (title, duration = 2000) => {
  uni.showToast({
    title,
    icon: 'none',
    duration
  })
}

// 确认对话框
export const showConfirm = (content, title = '提示') => {
  return new Promise((resolve) => {
    uni.showModal({
      title,
      content,
      success: (res) => {
        resolve(res.confirm)
      }
    })
  })
}

// 拨打电话
export const makePhoneCall = (phoneNumber) => {
  uni.makePhoneCall({
    phoneNumber,
    fail: () => {
      showError('拨打电话失败')
    }
  })
}

// 复制到剪贴板
export const copyToClipboard = (data) => {
  return new Promise((resolve, reject) => {
    uni.setClipboardData({
      data,
      success: () => {
        showSuccess('复制成功')
        resolve()
      },
      fail: (error) => {
        showError('复制失败')
        reject(error)
      }
    })
  })
}

// 预览图片
export const previewImage = (urls, current = 0) => {
  uni.previewImage({
    urls,
    current: typeof current === 'number' ? urls[current] : current,
    fail: () => {
      showError('预览图片失败')
    }
  })
}

// 获取系统信息
export const getSystemInfo = () => {
  return new Promise((resolve, reject) => {
    uni.getSystemInfo({
      success: resolve,
      fail: reject
    })
  })
}

// 获取网络状态
export const getNetworkType = () => {
  return new Promise((resolve, reject) => {
    uni.getNetworkType({
      success: resolve,
      fail: reject
    })
  })
}

// 震动反馈
export const vibrateShort = () => {
  uni.vibrateShort({
    fail: () => {
      console.log('震动反馈失败')
    }
  })
}

// 震动反馈（长）
export const vibrateLong = () => {
  uni.vibrateLong({
    fail: () => {
      console.log('震动反馈失败')
    }
  })
}

// 设置导航栏标题
export const setNavigationBarTitle = (title) => {
  uni.setNavigationBarTitle({
    title
  })
}

// 设置导航栏颜色
export const setNavigationBarColor = (frontColor, backgroundColor) => {
  uni.setNavigationBarColor({
    frontColor,
    backgroundColor
  })
}

// 显示导航栏加载
export const showNavigationBarLoading = () => {
  uni.showNavigationBarLoading()
}

// 隐藏导航栏加载
export const hideNavigationBarLoading = () => {
  uni.hideNavigationBarLoading()
}

// 页面滚动到顶部
export const pageScrollTo = (scrollTop = 0, duration = 300) => {
  uni.pageScrollTo({
    scrollTop,
    duration
  })
}

// 获取当前页面栈
export const getCurrentPages = () => {
  return getCurrentPages()
}

// 网咖特色工具函数

// 计算座位使用时长
export const calculateSeatDuration = (startTime, endTime) => {
  const start = new Date(startTime)
  const end = new Date(endTime)
  const duration = end.getTime() - start.getTime()
  
  const hours = Math.floor(duration / (1000 * 60 * 60))
  const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60))
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  }
  return `${minutes}分钟`
}

// 计算费用
export const calculateCost = (hourlyRate, duration) => {
  return hourlyRate * duration
}

// 格式化座位号
export const formatSeatNumber = (seatNumber) => {
  if (!seatNumber) return ''
  
  // 如果是数字，转换为字母+数字格式
  if (typeof seatNumber === 'number') {
    const row = Math.floor((seatNumber - 1) / 8)
    const col = (seatNumber - 1) % 8 + 1
    return `${String.fromCharCode(65 + row)}${col}`
  }
  
  return seatNumber
}

// 获取会员等级颜色
export const getMemberLevelColor = (level) => {
  const colors = {
    0: '#86868b', // 普通会员
    1: '#c0c0c0', // 银卡会员
    2: '#ffd700', // 金卡会员
    3: '#ff9500', // VIP会员
    4: '#af52de'  // 钻石会员
  }
  return colors[level] || colors[0]
}

// 获取订单状态颜色
export const getOrderStatusColor = (status) => {
  const colors = {
    pending: '#ff9500',
    confirmed: '#007aff',
    in_progress: '#34c759',
    completed: '#8e8e93',
    cancelled: '#ff3b30'
  }
  return colors[status] || colors.pending
}

export default {
  formatTime,
  formatRelativeTime,
  formatMoney,
  formatPhone,
  validatePhone,
  validateEmail,
  debounce,
  throttle,
  deepClone,
  generateId,
  showLoading,
  hideLoading,
  showSuccess,
  showError,
  showConfirm,
  makePhoneCall,
  copyToClipboard,
  previewImage,
  getSystemInfo,
  getNetworkType,
  vibrateShort,
  vibrateLong,
  setNavigationBarTitle,
  setNavigationBarColor,
  showNavigationBarLoading,
  hideNavigationBarLoading,
  pageScrollTo,
  getCurrentPages,
  calculateSeatDuration,
  calculateCost,
  formatSeatNumber,
  getMemberLevelColor,
  getOrderStatusColor
}
